package com.learn.kotlinlearndemolist.service

import android.accessibilityservice.AccessibilityService
import android.util.Log
import android.view.accessibility.AccessibilityEvent
import android.view.accessibility.AccessibilityNodeInfo
import android.widget.Button


class DetectionService : AccessibilityService() {

    companion object {
        val TAG = DetectionService::class.simpleName
    }

    override fun onAccessibilityEvent(accessibilityEvent: AccessibilityEvent) {
        if (accessibilityEvent.eventType == AccessibilityEvent.TYPE_WINDOW_STATE_CHANGED) {
            val className = accessibilityEvent.className.toString()
            val packageName = accessibilityEvent.packageName.toString()
            Log.d(TAG, "onAccessibilityEvent: source = ${accessibilityEvent.source}")
            if (packageName == "com.learn.kotlinlearndemolist"
                && className == "com.learn.kotlinlearndemolist.view.CustomDialog"
            ) {
                Button::class.simpleName?.let { click(accessibilityEvent, "确认", it) }
            }
            //监听当前窗口变化，获取Package名和Class名
            Log.d(TAG, "shine:onAccessibilityEvent,className =$className")
            Log.d(TAG, "shine:onAccessibilityEvent,packageName=$packageName")
        }
    }

    override fun onInterrupt() {

    }

    /**
     * 模拟点击
     * @param event 事件
     * @param text 按钮文字
     * @param widgetType 按钮类型，如android.widget.Button，android.widget.TextView
     */
    private fun click(event: AccessibilityEvent, text: String, widgetType: String) {
        Log.d(TAG, "click: text = $text")
        // 事件页面节点信息不为空
        if (event.source != null) {
            // 根据Text搜索所有符合条件的节点, 模糊搜索方式; 还可以通过ID来精确搜索findAccessibilityNodeInfosByViewId
            val stopNodes = event.source?.findAccessibilityNodeInfosByText(text)
            Log.d(TAG, "click: stopNodes = $stopNodes")
            // 遍历节点
            if (!stopNodes.isNullOrEmpty()) {
                var node: AccessibilityNodeInfo
                for (i in stopNodes.indices) {
                    node = stopNodes[i]
                    // 判断按钮类型
                    if (node.className == widgetType) {
                        // 可用则模拟点击
                        if (node.isEnabled) {
                            Log.d(TAG, "click: isEnabled = $node")
                            node.performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        }
                    }
                }
            }
        }
    }

}